<template>
  <div class="list-common-table">
    <t-form
      ref="form"
      :data="formDataQueryHost"
      :label-width="80"
      colon
      @reset="onReset"
      @submit="onSubmit"
      :style="{ marginBottom: '20px' }"
    >
      <t-row>
        <t-col :span="10">
          <t-row :gutter="[16, 24]">
            <t-col :flex="1">
              <t-form-item label="主机名称" name="host_name">
                <t-input
                  v-model="formDataQueryHost.host_name"
                  class="form-item-content"
                  type="search"
                  placeholder="请输入主机名称"
                  :style="{ minWidth: '200px' }"
                />
              </t-form-item>
            </t-col>
            <t-col :flex="1">
              <t-form-item label="链接状态" name="status">
                <t-select
                  v-model="formDataQueryHost.status"
                  class="form-item-content`"
                  :options="LINK_STATUS_OPTIONS"
                  placeholder="请选择链接状态"
                />
              </t-form-item>
            </t-col>
            <t-col :flex="1">
              <t-form-item label="ip" name="ipaddr">
                <t-input
                  v-model="formDataQueryHost.ipaddr"
                  class="form-item-content"
                  placeholder="支持内网外网搜索"
                  :style="{ minWidth: '200px' }"
                />
              </t-form-item>
            </t-col>
            <t-col :flex="1">
              <t-form-item label="创建人" name="create_user">
                <t-select v-model="formDataQueryHost.create_user" class="form-item-content`" placeholder="请选择创建人" @focus="loadUserList">
                  <t-option v-for="item in options2" :value="item.value" :label="item.label" :key="item.value"></t-option>
                </t-select>
              </t-form-item>
            </t-col>
          </t-row>
        </t-col>

        <t-col :span="2" class="operation-container">
          <t-button theme="primary" type="submit" :style="{ marginLeft: '8px' }"> 查询</t-button>
          <t-button type="reset" variant="base" theme="default"> 重置</t-button>
        </t-col>
      </t-row>
    </t-form>
    <t-row justify="space-between">
      <div class="left-operation-container">
        <t-button @click="handleClickRegister"> 注册主机</t-button>
<!--        <t-button variant="base" theme="default" :disabled="!selectedRowKeys.length" @click="handleHostDelete"> 删除主机-->
        <t-button variant="base" theme="default" :disabled="!selectedRowKeys.length" @click="visible3 = true"> 删除主机
        </t-button>
        <!--        <p v-if="!!selectedRowKeys.length" class="selected-count">已选{{ selectedRowKeys.length }}项</p>-->
      </div>
      <t-space style="width: 100%" direction="vertical">
        <div v-if="selectedRowKeys.length > 0" class="selected-row-alert">
          <t-alert theme="success" :message="'已选' + selectedRowKeys.length + '项'"/>
        </div>
        <div v-else class="selected-row-alert">
          <t-alert theme="success" message="已选0项"/>
        </div>
      </t-space>

    </t-row>
    <div class="table-container">
      <t-table
        :data="data"
        :columns="columns"
        rowKey="id"
        :verticalAlign="verticalAlign"
        :hover="hover"
        :pagination="pagination"
        :selected-row-keys="selectedRowKeys"
        @page-change="rehandlePageChange"
        @change="rehandleChange"
        @select-change="rehandleSelectChange"
        :loading="dataLoading"
        :headerAffixedTop="true"
        :headerAffixProps="{ offsetTop, container: getContainer }"
      >
        <template #ssh_state="{ row }">
          <t-tag v-if="row.ssh_state === LINK_STATUS.FAIL" theme="danger" variant="light">链接失败</t-tag>
          <t-tag v-if="row.ssh_state === LINK_STATUS.EXCEPTION" theme="warning" variant="light">链接异常</t-tag>
          <t-tag v-if="row.ssh_state === LINK_STATUS.SUCCESS" theme="success" variant="light">链接成功</t-tag>
        </template>
        <template #op="slotProps">
          <a class="t-button-link" @click="handleHostConn(slotProps.row)">链接</a>
          <a class="t-button-link" @click="handleClickEdit(slotProps.row)">编辑</a>
          <a class="t-button-link" @click="handleClickDetails(slotProps.row)">详情</a>
        </template>
      </t-table>
    </div>
    <!-- 注册主机弹窗 -->
    <host-dialog
      :visible="formVisible"
      :formData="formDataAddHost"
      :title="dialogTitle"
      @submit="handleDialogSubmit"
      @cancel="handleDialogCancel"
    />
    <!-- 详情信息弹窗 -->
    <t-dialog header="机器信息" :visible.sync="visible" @confirm="onConfirm" :closeBtn="false">
      <div slot="body">
        <div class="dialog-info-block">
          <div v-for="(item, index) in hostInfoData" :key="index" class="info-item">
            <h1>{{ item.name }}:</h1>
            <span
              :class="{
                ['green']: item.type && item.type.value === 'green',
                ['blue']: item.type && item.type.value === 'blue',
              }"
            >{{ item.value }}</span
            >
          </div>
        </div>
      </div>
    </t-dialog>
    <!--删除确认-->
    <t-dialog
      theme="warning"
      header="删除确认"
      body="确认删除选中的机器吗"
      :visible.sync="visible3"
      @confirm="onConfirmDel"
      :onClose="close3"
      :cancelBtn="null"
    />


  </div>
</template>
<script>
import {prefix} from '@/config/global';
import HostDialog from './HostDialog.vue';
import {
  LINK_STATUS,
  LINK_STATUS_OPTIONS,
} from '@/constants';

export default {
  name: 'list-table',
  components: {
    HostDialog,
  },
  data() {
    return {
      LINK_STATUS,
      LINK_STATUS_OPTIONS,
      prefix,
      visible3: false,
      formDataQueryHost: {
        host_name: '',
        ipaddr: '',
        status: undefined,
        create_user: '',
      },
      formDataAddHost: {
        id: '',
        host_name: '',
        inside_ipaddr: '',
        outside_ipaddr: '',
        inside_or_outside: null,
        ssh_port: '22',
        username: '',
        password: '',
      },
      options2: [],
      data: [],
      dataLoading: false,
      hostInfoData: [],
      value: 'first',
      selectedRowKeys: [],
      columns: [
        {colKey: 'row-select', type: 'multiple', width: 64, fixed: 'left'},
        {
          title: 'ID',
          fixed: 'left',
          width: 50,
          align: 'left',
          ellipsis: true,
          colKey: 'id',
        },
        {
          title: '主机名称',
          width: 150,
          ellipsis: true,
          colKey: 'host_name',
        },
        {title: '链接状态', colKey: 'ssh_state', width: 100, cell: {col: 'ssh_state'}},
        {
          title: '内网IP',
          width: 100,
          ellipsis: true,
          colKey: 'inside_ipaddr',
        },
        {
          title: '外网IP',
          width: 100,
          ellipsis: true,
          colKey: 'outside_ipaddr',
        },
        {
          title: 'cpu',
          width: 70,
          ellipsis: true,
          colKey: 'cpu',
        },
        {
          title: 'Mem',
          width: 70,
          ellipsis: true,
          colKey: 'memory',
        },
        {
          title: '磁盘',
          width: 100,
          ellipsis: true,
          colKey: 'disk',
        },
        {
          title: '内网带宽',
          width: 100,
          ellipsis: true,
          colKey: 'network',
        },
        {
          title: '创建人',
          width: 100,
          ellipsis: true,
          colKey: 'create_user',
        },
        {
          title: '创建时间',
          width: 100,
          ellipsis: true,
          colKey: 'create_time',
        },

        {
          align: 'left',
          fixed: 'right',
          width: 200,
          colKey: 'op',
          title: '操作',
        },
      ],
      rowKey: 'id',
      visible: false,
      formVisible: false,
      tableLayout: 'auto',
      verticalAlign: 'top',
      bordered: true,
      hover: true,
      rowClassName: (rowKey) => `${rowKey}-class`,
      // 与pagination对齐
      pagination: {
        defaultPageSize: 20,
        total: 100,
        defaultCurrent: 1,
      },
      confirmVisible: false,
      deleteIdx: -1,
      rules: {
        name: [{required: true, message: '请输入产品名称', type: 'error'}],
      },
      dialogTitle: '',
      textareaValue: '',
    };
  },
  computed: {
    confirmBody() {
      if (this.deleteIdx > -1) {
        const {name} = this.data?.[this.deleteIdx];
        return `删除后，${name}的链连接信息将被清空，且无法恢复`;
      }
      return '';
    },
    offsetTop() {
      return this.$store.state.setting.isUseTabsRouter ? 48 : 0;
    },
  },
  mounted() {
    this.dataLoading = true;
    this.$request
      .get('api/query/hosts_list')
      .then((res) => {
        console.log("主机列表~~~~~", res)
        console.log("data中的数据~", res.data)
        if (res.data.code === '000') {
          this.data = res.data.data;
          console.log("拿到数据进行赋值", JSON.stringify(this.data))
          this.pagination = {
            ...this.pagination,
            total: this.data.length,
          };
        }
      })
      .catch((e) => {
        console.log(e);
      })
      .finally(() => {
        this.dataLoading = false;
      });

  },
  methods: {
    getContainer() {
      return document.querySelector('.tdesign-starter-layout');
    },
    rehandlePageChange(curr, pageInfo) {
      console.log('分页变化', curr, pageInfo);
    },
    rehandleChange(changeParams, triggerAndData) {
      console.log('统一Change', changeParams, triggerAndData);
    },
    //加载出用户
    loadUserList() {
      this.$request
        .get('api/user/query/user_list')
        .then((res) => {
          console.log("用户列表~~~~~", res.data)
          if (res.data.code === '000') {
            const transformedData = res.data.data.map((item) => ({
              value: item.id,
              label: item.username,
            }));
            this.options2 = transformedData
            console.log('筛选条件中的用户列表~~~~~~~~',this.options2)
          }
        })
        .catch((e) => {
          console.log(e);
        })
        .finally(() => {
          this.dataLoading = false;
        });
    },
    // 清空搜索框的内容
    onReset(data) {
      console.log(data);
      this.formDataQueryHost = {
        host_name: '',
        ipaddr: '',
        status: undefined,
        create_user: ''
      };
      window.location.reload(); // 刷新页面

    },
    // 按照选择的条件进行搜索
    onSubmit({validateResult, firstError}) {
      if (validateResult === true) {
        this.dataLoading = true;

        // 构建筛选参数
        const params = {
          host_name: this.formDataQueryHost.host_name,
          ipaddr: this.formDataQueryHost.ipaddr,
          status: this.formDataQueryHost.status,
          create_user: this.formDataQueryHost.create_user
        };

        // 发起请求，获取筛选结果
        this.$request
          .get('api/query/hosts_list', {params})
          .then((res) => {
            if (res.data.code === '000') {
              this.data = res.data.data;
              this.pagination = {
                ...this.pagination,
                total: this.data.length
              };
            }
            this.$message.success('提交成功');
          })
          .catch((e) => {
            console.log(e);
          })
          .finally(() => {
            this.dataLoading = false;
          });
      } else {
        console.log('Errors: ', validateResult);
        this.$message.warning(firstError);
      }
    },
    // 链接机器，看机器信息是否链接成功
    handleHostConn(row) {
      console.log("row", row)
      let params = {};
      params = {
        param:{id: row.id},
        op_type: '3'
      };
      console.log('链接机器看看能不能链接上:', params);

      this.$request
        .post('/api/operate/hosts', params)
        .then((res) => {

          this.$message.success('提交成功');
        })
        .catch((e) => {
          console.log(e);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 点击后查看机器详情信息
    handleClickDetails(row) {
      this.visible = true;
      this.dataLoading = true;
      // 构建筛选参数
      const params = {
        host_id: row.id,
      };

      // 发起请求，获取筛选结果
      this.$request
        .get('/api/query/hosts_info/', {params})
        .then((res) => {
          if (res.data.code === '000') {
            this.hostInfoData = res.data.data;
          }
        })
        .catch((e) => {
          console.log(e);
        })
        .finally(() => {
          this.dataLoading = false;
        });
    },
    // 主机删除--单行删除
    handleHostDelete() {
      if (this.selectedRowKeys.length > 0) {
        const ids = this.selectedRowKeys.map((key) => this.data[key].id);
        console.log("我选中的行", ids)
        const params = {
          ids: ids,
          op_type: '0'
        };
        this.$request
          .post('/api/operate/hosts', params)
          .then((res) => {
            this.$message.success('提交成功');
            window.location.reload();
          })
          .catch((e) => {
            console.log(e);
          })
          .finally(() => {
            this.loading = false;
          });
      } else {
        this.$message.warning('请选择要删除的主机');
      }
    },
    // 主机删除，全局删除
    onConfirmDel(){
      if (this.selectedRowKeys.length > 0) {
        console.log("选中的那一行数据~--selectedData",JSON.stringify(this.selectedRowKeys))
        const params = {
          ids: this.selectedRowKeys,
          op_type: '0'
        };
        this.$request
          .post('/api/operate/hosts', params)
          .then((res) => {
            this.$message.success('提交成功');
            this.visible3 = false;
            window.location.reload();
          })
          .catch((e) => {
            console.log(e);
          })
          .finally(() => {
            this.loading = false;
          });
      } else {
        this.$message.warning('请选择要删除的主机');
      }
    },

    //选择一行，拿到哪一行的内容数据
    rehandleSelectChange(value, {selectedRowData}) {
      this.selectedRowKeys = value;
      console.log("这是拿到的值吗",value,selectedRowData);
    },
    // 点击注册主机后，弹窗弹出一个新的窗口，默认进来数据为空
    handleClickRegister() {
      this.formVisible = true;
      this.dialogTitle = '注册主机';
      this.formDataAddHost = {
        id: '',
        host_name: '',
        inside_ipaddr: '',
        outside_ipaddr: '',
        inside_or_outside: "0",
        username: '',
        password: '',
        ssh_port:''
      };

    },
    // 编辑的时候，拿到编辑的信息
    handleClickEdit(row) {
      this.formVisible = true;
      this.dialogTitle = '编辑主机信息'
      this.$nextTick(() => {
        this.formDataAddHost = {...row};
      });
    },
    //弹窗提交
    handleDialogSubmit(formDataAddHost) {
      // 处理弹窗提交事件
      // 在这里可以更新父组件的数据或执行其他逻辑
      // 更新父组件的数据
      this.formDataAddHost = {...formDataAddHost};
      // 关闭弹窗
      this.formVisible = false;
    },
    handleDialogCancel() {
      // 处理弹窗取消事件
      this.formVisible = false;
      // 其他逻辑
    },
    onConfirm() {
      this.visible = false;
    },
    close3() {
      // this.chainConnLog = false;
      console.log('close3')
    },
  },
};
</script>

<style lang="less" scoped>
@import '@/style/variables.less';

.selected-row-alert {
  padding: 8px;
  margin-top: 8px;
  margin-bottom: 8px;
}

.selected-row-alert .td-alert-content {
  padding: 6px;
  line-height: 1;
}

.list-common-table {
  background-color: var(--td-bg-color-container);
  padding: 30px 32px;
  border-radius: var(--td-radius-default);
}

.form-item-content {
  width: 50%;
}

.selected-count {
  display: inline-block;
  margin-left: var(--td-comp-margin-s);
  color: var(--td-text-color-secondary);
}

.operation-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.operation-ad-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin: 20px;
}

.payment-col {
  display: flex;

  .trend-container {
    display: flex;
    align-items: center;
    margin-left: 8px;
  }
}

.t-button + .t-button {
  margin-left: var(--td-comp-margin-s);
}

</style>
